package org.codehaus.activemq.transport;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.jms.JMSException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class TransportServerChannelSupport
  implements TransportServerChannel
{
  private static final Log log = LogFactory.getLog(TransportServerChannelSupport.class);
  private TransportChannelListener listener;
  private List channels = new ArrayList();

  public void start() throws JMSException {
    if (this.listener == null)
      throw new JMSException("Must have a TransportChannelListener attached!");
  }

  public synchronized void stop()
  {
    for (Iterator iter = this.channels.iterator(); iter.hasNext(); ) {
      TransportChannel channel = (TransportChannel)iter.next();
      channel.stop();
    }
  }

  public void setTransportChannelListener(TransportChannelListener listener) {
    this.listener = listener;
  }

  protected synchronized void addClient(TransportChannel channel) {
    if (this.listener == null) {
      log.warn("No listener attached, cannot add channel: " + channel);
    }
    else {
      this.listener.addClient(channel);
      channel.setTransportChannelListener(this.listener);
      this.channels.add(channel);
    }
  }
}